<template>

  <div>

    <data-table
      ref="pagingTable"
      :options="options"
      :list-query="listQuery"
      @multi-actions="handleMultiAction"
    >

      <template slot="filter-content">

        <el-input v-model="listQuery.params.userName" style="width: 200px" placeholder="搜索登录名" class="filter-item" />
        <el-input v-model="listQuery.params.realName" style="width: 200px" placeholder="搜索姓名" class="filter-item" />

        <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">
          添加
        </el-button>

      </template>

      <template slot="data-columns">

        <el-table-column
          type="selection"
          width="55"
        />

        <el-table-column
          align="center"
          label="用户名"
        >
          <template slot-scope="scope">
            <a @click="handleUpdate(scope.row)">{{ scope.row.userName }}</a>
          </template>

        </el-table-column>

        <el-table-column
          align="center"
          label="姓名"
          prop="realName"
        />

        <el-table-column
          align="center"
          label="角色"
          prop="roleIds"
        />

        <el-table-column
          align="center"
          label="创建时间"
          prop="createTime"
        />

        <el-table-column
          align="center"
          label="状态"
        >

          <template slot-scope="scope">
            {{ scope.row.state | stateFilter }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="准考证"
        >
          <template slot-scope="scope">
            <a @click="handleDown(scope.row)">下载</a>
          </template>

        </el-table-column>
      </template>
    </data-table>

    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="500px">

      <el-form :model="formData" label-position="left" label-width="100px">

        <el-form-item label="用户名">
          <el-input v-model="formData.userName" />
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="formData.password" placeholder="不修改请留空" type="password" />
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="formData.realName" />
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="formData.sex">
            <el-option
              label="男"
              value="男"
            />
            <el-option
              label="女"
              value="女"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="身份证号">
          <el-input v-model="formData.idNo" />
        </el-form-item>

        <el-form-item label="等级">
          <depart-tree-select v-model="formData.departId" :options="treeData" :props="defaultProps" />
        </el-form-item>

        <el-form-item label="角色">
          <meet-role v-model="formData.roles" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <file-upload v-model="formData.avatar" />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="random">随 机</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>

    </el-dialog>

  </div>

</template>

<script>
import DataTable from '@/components/DataTable'
import MeetRole from '@/components/MeetRole'
import { saveData } from '@/api/sys/user/user'
import DepartTreeSelect from '@/components/DepartTreeSelect'
import { fetchTree } from '@/api/sys/depart/depart'
import FileUpload from '@/components/FileUpload'

function downLoad(url, saveAs) {
  var oA = document.createElement('a')
  oA.download = saveAs// 设置下载的文件名，默认是'下载'
  oA.href = url
  document.body.appendChild(oA)
  oA.click()
  oA.remove()// 下载之后把创建的元素删除
}

function saveAsJPG(canvas) {
  return canvas.toDataURL('image/jpeg')
}

export default {
  name: 'SysUserList',
  components: { DepartTreeSelect, DataTable, MeetRole, FileUpload },
  filters: {

    // 订单状态
    userState(value) {
      const map = {
        '0': '正常',
        '1': '禁用'
      }
      return map[value]
    }
  },
  data() {
    return {

      treeData: [],
      defaultProps: {
        value: 'id',
        label: 'deptName',
        children: 'children'
      },
      dialogVisible: false,

      listQuery: {
        current: 1,
        size: 10,
        params: {
        }
      },

      formData: {
        avatar: ''
      },

      options: {
        // 列表请求URL
        listUrl: '/exam/api/sys/user/paging',
        // 启用禁用
        stateUrl: '/sys/user/state',
        deleteUrl: '/exam/api/sys/user/delete',
        // 批量操作列表
        multiActions: [
          {
            value: 'enable',
            label: '启用'
          }, {
            value: 'disable',
            label: '禁用'
          },
          {
            value: 'delete',
            label: '删除'
          }
        ]
      }
    }
  },

  created() {
    fetchTree({}).then(response => {
      this.treeData = response.data
    })
  },

  methods: {

    handleUploadSuccess(response) {
      // 上传图片赋值
      this.formData.avatar = response.data.url
    },

    handleAdd() {
      this.formData = {}
      this.dialogVisible = true
    },

    handleUpdate(row) {
      this.dialogVisible = true
      this.formData = row
      this.formData.roles = row.roleIds.split(',')
      this.formData.password = null

      console.log(JSON.stringify(this.formData))
    },

    departSelected(data) {
      this.formData.departId = data.id
    },
    handleSave() {
      saveData(this.formData).then((data) => {
        console.log(data)
        this.$message({
          type: 'success',
          message: '用户修改成功!'
        })
        this.dialogVisible = false
        this.$refs.pagingTable.getList()
      })
    },
    random() {
      const date = new Date()
      let random = Math.floor(Math.random() * 100000) + ''
      switch (random.length) {
        case 1:
          random = '0000' + random
          break
        case 2:
          random = '000' + random
          break
        case 3:
          random = '00' + random
          break
        case 4:
          random = '0' + random
          break
      }
      this.$set(this.formData, 'userName', '3702' + date.getFullYear() + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + random)
      this.$set(this.formData, 'password', random)
    },

    // 批量操作监听
    handleMultiAction(obj) {
      if (obj.opt === 'cancel') {
        this.handleCancelOrder(obj.ids)
      }
    },
    handleDown(row) {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      // ctx.fillStyle = '#0000ff'// 填充颜色
      // ctx.fillRect(10, 10, 70, 70) // 填充矩形，xy宽高(像素)
      // ctx.lineWidth = 20// 边框宽度
      // ctx.lineCap = 'round'// 线条末端形状，butt平头，round圆头，square方头，
      // ctx.lineJoin = 'round'// 线条交叉方式，round圆交，bevel斜交，miter斜接
      // ctx.strokeStyle = 'red' // 描边颜色
      // ctx.strokeRect(50, 50, 50, 50) // 描边矩形
      // ctx.clearRect(50, 50, 20, 20) // 清除一块矩形区域
      const img = new Image()
      img.src = require('@/assets/ticket.jpg')
      img.onload = () => { // 等背景图片加载成功后
        canvas.width = 500
        canvas.height = 756
        ctx.drawImage(img, 0, 0, 500, 713)

        ctx.font = '16px Microsoft YaHei'
        ctx.fillStyle = '#67717b'
        ctx.fillText(row.realName, 165, 197)
        ctx.fillText(row.sex, 165, 241)

        ctx.fillText('身份证', 165, 285)
        ctx.fillText(row.idNo, 165, 331)
        let item = null
        this.treeData.find(function(departlist) {
          for (const itemElement of departlist.children) {
            if (itemElement.id === row.departId) {
              item = itemElement
              return true
            }
          }
        })
        ctx.fillText(item.deptName.split(' ')[1], 165, 375)
        ctx.fillText(item.deptName.split(' ')[0], 165, 420)

        ctx.fillText(row.userName, 165, 464)
        ctx.fillText(row.userName.substr(10), 165, 509)

        ctx.fillText('https://test.tpttest.com', 165, 553)
        ctx.fillText('全程AI智能监考', 165, 597)
        // ctx.fillText('居家场景下的线上考试', 165, 620)

        const avatar = new Image()
        avatar.src = row.avatar
        avatar.crossOrigin = 'Annoymous'
        avatar.onload = () => {
          const dpi = avatar.height / avatar.width
          ctx.drawImage(avatar, 358, 170, 96, 96 * dpi)
          downLoad(saveAsJPG(canvas), row.realName)
        }
      }
    }
  }
}
</script>
